package models

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
	"newGame/utils"
	"strconv"
)

type PAGE uint

//注册界面
func (page *PAGE) PGFC0001(c *gin.Context) {
	var (
		uuidStr string
	)
	uuidStr = utils.GenerateUuid()
	c.SetCookie("SessionId", uuidStr, 86400, "/api", "127.0.0.1", false, false)
	c.HTML(200, "register", nil)
}

//登陆界面
func (page *PAGE) PGFC0002(c *gin.Context) {
	var (
		uuidStr string
	)
	uuidStr = utils.GenerateUuid()
	c.SetCookie("SessionId", uuidStr, 86400, "/api", "127.0.0.1", false, false)
	c.HTML(200, "login", nil)
}

//普通地图界面
func (page *PAGE) PGFC0003(c *gin.Context) {
	var (
		err error
		ok  bool
		mapType,
		mapText,
		id  string
		mapData     map[string]interface{}
		npcList     []interface{}
		monsterList []interface{}
	)
	id = c.Query("P1")
	mapType = "stableMap"
	if mapText = Db.RedisDb.HGet(mapType, id).Val(); mapText == "" {
		c.HTML(403, "403", nil)
		return
	}
	if mapData, err = utils.UnMarshal(mapText); err != nil {
		c.HTML(500, "500", nil)
		return
	}
	mapData = mapData["unmarshalData"].(map[string]interface{})
	if npcList, ok = mapData["npcList"].([]interface{}); !ok {
		npcList = []interface{}{}
	}
	if monsterList, ok = mapData["monsterList"].([]interface{}); !ok {
		monsterList = []interface{}{}
	}
	c.HTML(200, "stableMap", gin.H{
		"mapData":     mapData,
		"npcData":     npcList,
		"monsterData": monsterList,
	})
}

//NPC界面
func (page *PAGE) PGFC0004(c *gin.Context) {
	var (
		npcText,
		id string
		npcData map[string]interface{}
		err     error
	)
	id = c.Query("P1")
	npcText = Db.RedisDb.HGet("npcList", id).Val()
	if npcData, err = utils.UnMarshal(npcText); err != nil {
		log.Fatal(err)
	}
	c.HTML(200, "npc", gin.H{
		"npcData": npcData["unmarshalData"],
	})
}

//背包界面
func (page *PAGE) PGFC0005(c *gin.Context) {
	var (

		cursor *mongo.Cursor
		userId string
		result     map[string]interface{}
		err        error
		searchData bson.M
		pg,
		limit,
		skip       int64
	)
	limit,_ = strconv.ParseInt(c.Query("P2"),10,64)
	pg,_ = strconv.ParseInt(c.Query("P3"),10,64)
	userId = utils.GetStringContextArg("userId", c)
	searchData = bson.M{
		"userId": userId,
	}
	skip = limit * pg

	cursor,err = Db.MongoDb.Database("games").Collection("knapsack").Find(nil, searchData, &options.FindOptions{Projection: bson.D{{"knapsack", 1}}, Limit: &limit, Skip: &skip})
	if err != nil{
		fmt.Println(err)
		c.HTML(500, "500", nil)
		return
	}
	for cursor.Next(nil){
		result = make(map[string]interface{})
		if err = cursor.Decode(&result);err != nil{
			fmt.Println(err)
			c.HTML(500, "500", nil)
			return
		}

	}
	c.HTML(403, "403", nil)
	return

	c.HTML(200, "npc", result)
}
